import { Config } from '@/utils/config.js';

export function request(url="",data={},method="GET"){
		return new Promise((resolve, reject) => {
			try {
				uni.request({
					url: Config.restUrl + url,
					method: method,
					data: data,
					header: {
						Authorization:uni.getStorageSync("token") || ''
					},
					success: (res) => {

						let dataCode = res.data.code ?? 0;
						let statusCode = res.statusCode.toString() ?? 400;
						var startChar = statusCode.charAt(0);
						//请求成功 服务端报错
						if (!(startChar == '2')){

							console.log(statusCode+"请求失败", res.data.message);

							if(statusCode==409){
								uni.showModal({
									title: res.data.message,
									cancelText:"暂不登录",
									success: (res)=> {
										if (res.confirm) {
											uni.removeStorageSync("token");
											//uni.clearStorageSync();
											uni.reLaunch({
												url: '/pages/login/login'
											});
										}else{
											uni.reLaunch({
												url: '/pages/index/index'
											});
										}
									},
									fail:(error)=>{
										console.log("请求失败",error);
									}
								});
							}else{
								uni.showModal({
									title: res.data.message,
									icon: "none"
								});
							}

							reject(res.data);
						}else{
							if (dataCode == 1) {
								console.log("resolve", dataCode);
								resolve(res.data.data);
							} else {
								console.log("reject", dataCode);
								uni.showModal({
									title:  res.data.message,
									icon: "none"
								});
								reject(res);
							}
						}


					},
					fail: (err) => {
						console.log(err);
						uni.showModal({
							title: err.message ?? "网络请求失败",
							icon: "none"
						});
						reject(err);
					},
					complete: (result) => {
						console.log("complete" + result);
					}
				});
			} catch (error) {
				console.log("Request error:", error);
				uni.showModal({
					title: "请求异常",
					content: error.message || "未知错误",
					icon: "none"
				});
				reject(error);
			}
		});
	}
